//index.js
//获取应用实例
let app = getApp();
var amapFile = require('../../libs/amap-wx.js'); //如：..­/..­/libs/amap-wx.js
var markersData = [];
Page({
  data: {
    //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isHide: false,
    markers: [],
    latitude: '',
    longitude: '',
    textData: {},
    markerId: 0,
    controls: [{
      id: 0,
      position: {
        left: 10,
        top: 350,
        width: 40,
        height: 40
      },
      iconPath: "/img/yuandian.png",
      clickable: true
    }],
    toView: 'red',
    scrollTop: 100,
    id_token: '',
    flagButton: '开始监控',
    personname: '',
    backgroundColor: '#4D8AD7',
    catchIcon: '../../img/marker_checked.png',
    friendList: [],
    selectedUsername: '我',
    admin_flag: false,
    lastOpenid: '',
    currentTaskid: '',
    shareflag: false,
    temporaryhead: '',
    temporaryusername: ''
  },
  // makertap: function (e) {
  //   var id = e.markerId;
  //   var that = this;
  //   that.showMarkerInfo(markersData, id);
  //   that.changeMarkerColor(markersData, id);
  // },
  onLoad: function(options) {
    var that = this;
    console.log(options)
    if (JSON.stringify(options) != "{}") {
      that.setData({
        shareflag: true
      })
    }
    if (app.globalData.isfirst == true) {
      app.globalData.isfirst = false;
    }
    app.watch(that.watchBack);
    this.dialog = this.selectComponent('#dialog');
    // this.dialog.show();

    wx.login({
      success: res => {
        console.log("获取code");
        console.log(res);
        // 发送 res.code 到后台换取用户token
        wx.request({
          url: app.globalData.url + '/app-users/userlogin',
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            code: res.code
          },
          success: res => {
            // 获取到用户的token，存储在本地
            console.log('app调用成功');
            console.log(res);
            wx.setStorageSync('id_token', res.data.idToken);
            wx.setStorageSync('open_id', res.data.userDTO.login);
            wx.setStorageSync('authorities', res.data.userDTO.authorities);


            // 创建Socket
            wx.connectSocket({
              //url: 'ws://localhost:8080/ws/asset',
              url: 'wss://www.cheerylab.cn/ws/asset',
              header: {
                'Authorization': 'Bearer ' + res.data.idToken
              },
              success: function(ws_res) {
                console.log('WebSocket连接创建', ws_res);
                if (that.data.shareflag == true) {
                  if (options.realtion == "0" && options.id != wx.getStorageSync('open_id')) {
                    that.createRelation(options.id, wx.getStorageSync('open_id'));
                    that.updateAuthority("1");
                  } else {
                    that.createRelation(wx.getStorageSync('open_id'), options.id);
                    that.updateAuthority("0");
                  }
                }
              },
              fail: function(err) {
                wx.showToast({
                  title: '网络异常！',
                })
                console.log(err)
              },
            });



            // var dialog = this.selectComponent('#dialog');
            var authorities = wx.getStorageSync('authorities');

            if (authorities.indexOf("ROLE_NONE") > -1 && that.data.shareflag == false) {
              that.dialog.show();
            }
            if (authorities.indexOf("ROLE_ADMIN") > -1) {
              that.setData({
                admin_flag: true
              })
            }




          }
        });
      }
    });
    // 查看是否授权
    wx.getSetting({
      success: function(res) {
        if (res.authSetting['scope.userInfo']) {
          app.globalData.userInfo = wx.getStorageSync('userInfo');

        } else {
          // 用户没有授权
          // 改变 isHide 的值，显示授权页面
          that.setData({
            isHide: true
          });
        }
      }
    });
    var myAmapFun = new amapFile.AMapWX({
      key: '55e2591136e5d5aec54c9b1de500014e'
    });
    myAmapFun.getRegeo({
      success: function(data) {
        //成功回调
        console.log(data)
        const latitude = data[0].latitude;
        const longitude = data[0].longitude;
        that.getMap(latitude, longitude);
        that.setPositionName(latitude, longitude);

      },
      fail: function(info) {
        //失败回调
        console.log(info)
      }
    })
    // wx.getLocation({
    //   type: 'wgs84',
    //   success(res) {
    //     console.log(res)
    //     const latitude = res.latitude;
    //     const longitude = res.longitude;
    //     that.getMap(latitude, longitude);
    //     that.setPositionName(latitude, longitude);

    //   }
    // })


  },

  onReady: function() {

  },
  onShow: function() {

    this.getRelationList();


    // wx.onSocketMessage(function (message) {
    //   console.log(message)
    // })


  },




  //回到用户当前定位点
  clickcontrol(e) {
    let that = this;
    let {
      controlId
    } = e;
    let mpCtx = wx.createMapContext("map");
    mpCtx.moveToLocation();
    this.setData({
      selectedUsername: '我',
      catchIcon: '../../img/marker_checked.png'

    });
    var myAmapFun = new amapFile.AMapWX({
      key: '55e2591136e5d5aec54c9b1de500014e'
    });
    myAmapFun.getRegeo({
      success: function(data) {
        //成功回调
        console.log(data)
        const latitude = data[0].latitude;
        const longitude = data[0].longitude;
        that.getMap(latitude, longitude);
        that.setPositionName(latitude, longitude);

      },
      fail: function(info) {
        //失败回调
        console.log(info)
      }
    })
    // wx.getLocation({
    //   type: 'wgs84',
    //   success(res) {
    //     console.log(res)
    //     const latitude = res.latitude;
    //     const longitude = res.longitude;
    //     that.getMap(latitude, longitude);
    //     that.setPositionName(latitude, longitude);

    //   }
    // })

  },
  mapchange() {
    //console.log("改变视野");
  },
  setScrollTop: function() {
    this.setData({
      top: 80
    })
  },
  //点击用户头像事件
  bindViewTap: function(e) {
    var that = this;
    that.getRelationList();
    var openid = e.currentTarget.dataset.openid;
    that.setData({
      lastOpenid: openid,
    })
    var headimage = e.currentTarget.dataset.headimage;
    var name = e.currentTarget.dataset.name;
    //如果已经查看其他被监控者位置信息就结束掉
    if (that.data.lastOpenid != '') {
      that.endPositionlook();
    }
    wx.request({
      url: app.globalData.url + '/temporary-positions/looking',
      method: 'POST',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('id_token'),
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        admin_open_id: wx.getStorageSync('open_id'),
        guest_open_id: openid,
        flag: '开启',
        type: '实时'
      },
      success: res => {}
    });
    app.updateWebsockey().then(e => {
      console.log(e)
      //如果是家长身份的用户
      if (wx.getStorageSync('authorities').indexOf("ROLE_ADMIN") >= 0) {
        if (e.message == "该用户不在线，无法查看当前位置信息") {
          wx.showModal({
            content: e.message,
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                console.log('用户点击确定')
              }
            }
          });
          return;
        }

        wx.downloadFile({
          url: headimage,
          success(res) {
            console.log(res)
            that.setData({
              catchIcon: res.tempFilePath.replace("http:/", ''),
              temporaryhead: res.tempFilePath.replace("http:/", ''),
              selectedUsername: name,
              temporaryusername: name
            });
            // 发出获取当前位置的请求
            // that.getMap();
          }
        });
        that.getTaskState();

      }
    });

  },
  bindGetUserInfo: function(e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      var that = this;
      // 获取到用户的信息了，打印到控制台上看下
      console.log("用户的信息如下：");
      console.log(e.detail.userInfo);
      app.globalData.userInfo = e.detail.userInfo;
      //授权成功后,通过改变 isHide 的值，让实现页面显示出来，把授权页面隐藏起来
      that.setData({
        isHide: false
      });
      this.updateNickname();
      var authorities = wx.getStorageSync('authorities');
      if (authorities.indexOf("ROLE_NONE") > -1 && that.data.shareflag == false) {
        that.dialog.show();
      }
      that.getRelationList();

    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
        showCancel: false,
        confirmText: '返回授权',
        success: function(res) {
          // 用户没有授权成功，不需要改变 isHide 的值
          if (res.confirm) {
            console.log('用户点击了“返回授权”');
          }
        }
      });
    }
  },
  changeButton: function() {
    var that = this;
    console.log(that.data.flagButton)
    if (that.data.flagButton == "开始监控" && that.data.selectedUsername != '我') {
      wx.showModal({
        title: '开始监控',
        content: '监控开始后,若被监控人的超出安全范围则提醒您',
        confirmText: "确定",
        cancelText: "取消",
        success: function(res) {
          console.log(res);
          if (res.confirm) {
            console.log('用户点击主操作');
            that.startTask();

          } else {
            console.log('用户点击辅助操作')
          }
        }
      });
    } else if (that.data.selectedUsername == '我') {
      wx.showModal({
        content: '请在选择联系人后再进行监控操作',
        showCancel: false,
        success: function(res) {
          if (res.confirm) {
            console.log('请用户选择联系人')
          }
        }
      });
    } else {
      wx.showModal({
        title: '停止监控',
        content: '关闭监控后，无法确保被监控人在安全范围哦',
        confirmText: "确定",
        cancelText: "取消",
        success: function(res) {
          console.log(res);
          if (res.confirm) {
            console.log('用户点击主操作')
            that.stopTask();

          } else {
            console.log('用户点击辅助操作')
          }
        }
      });

    }



  },
  //修改用户微信昵称
  updateNickname: function() {
    wx.request({
      url: app.globalData.url + '/app-users/wechatname',
      method: 'PUT',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('id_token'),
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        open_id: wx.getStorageSync('open_id'),
        wechatname: app.globalData.userInfo.nickName,
        headimage: app.globalData.userInfo.avatarUrl
      },
      success: res => {}
    });
  },
  getMap: function(latitude, longitude) {
    var that = this;

    var myAmapFun = new amapFile.AMapWX({
      key: '55e2591136e5d5aec54c9b1de500014e'
    });
    myAmapFun.getRegeo({
      iconPath: that.data.catchIcon, //定位图片自己找个图标
      iconWidth: 22,
      iconHeight: 32,
      success: function(data) {
        console.log(data);
        var marker = [{
          id: data[0].id,
          latitude: latitude,
          longitude: longitude,
          iconPath: that.data.catchIcon,
          width: data[0].width,
          height: data[0].height
        }]
        that.setData({
          markers: marker
        });
        that.setData({
          latitude: latitude
        });
        that.setData({
          longitude: longitude
        });


        // that.setData({
        //   textData: {
        //     name: data[0].name,
        //     desc: data[0].desc
        //   }
        // })
      },
      fail: function(info) {}
    })

  },
  cancelEvent: function() {
    console.log(this.dialog.data.cancelText);
    this.dialog.close();
  },
  okEvent: function(e) {
    var that = this;
    console.log(this.dialog.data.okText);
    console.log(e)
    this.dialog.close();
    if (e.detail.indexOf("ROLE_ADMIN") > -1) {
      that.setData({
        admin_flag: true
      })
    }


  },
  getRelationList: function() {
    wx.request({
      url: app.globalData.url + '/relationships/state',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('id_token'),
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        main_open_id: wx.getStorageSync('open_id')
      },
      success: res => {
        console.log("得到的朋友列表")
        console.log(res);
        var datalist = res.data;
        if (datalist.length > 0) {
          let list = [];
          for (var i = 0; i < datalist.length; i++) {
            list.push({
              headimage: datalist[i].headImage,
              name: datalist[i].nickName,
              stateflag: datalist[i].flag,
              openid: datalist[i].openId
            })
          }
          this.setData({
            friendList: list
          })
          console.log(this.data.friendList)
        } else {
          console.log("该用户未有联系人");
        }

      }
    });

  },
  endPositionlook: function() {
    var that = this;
    wx.request({
      url: app.globalData.url + '/temporary-positions/looking',
      method: 'POST',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('id_token'),
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        admin_open_id: wx.getStorageSync('open_id'),
        guest_open_id: that.data.lastOpenid,
        flag: '关闭',
        type: '实时'
      },
      success: res => {}
    });
  },
  startTask: function() {
    var that = this;
    var myAmapFun = new amapFile.AMapWX({
      key: '55e2591136e5d5aec54c9b1de500014e'
    });
    myAmapFun.getRegeo({
      success: function(data) {
        //成功回调
        console.log(data)
        const latitude = data[0].latitude;
        const longitude = data[0].longitude;
        //开启监控任务
        wx.request({
          url: app.globalData.url + '/check-tasks',
          method: 'POST',
          header: {
            'Authorization': 'Bearer ' + wx.getStorageSync('id_token'),
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            admin_open_id: wx.getStorageSync('open_id'),
            guest_open_id: that.data.lastOpenid,
            origin_x: latitude,
            origin_y: longitude
          },
          success: res => {
            console.log("获得的任务信息")
            console.log(res)
            that.setData({
              flagButton: '停止监控',
              backgroundColor: '#f0443c',
              currentTaskid: res.data.id
            });

          }
        })

      },
      fail: function(info) {
        //失败回调
        console.log(info)
      }
    })
  },
  getTaskState: function() {
    var that = this;
    //获取监控状态
    wx.request({
      url: app.globalData.url + '/check-tasks/isdoing',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('id_token'),
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        admin_open_id: wx.getStorageSync('open_id'),
        guest_open_id: that.data.lastOpenid
      },
      success: res => {
        console.log("获得的任务状态信息");
        console.log(res)
        if (res.data > "0") {
          that.setData({
            flagButton: '停止监控',
            backgroundColor: '#f0443c',
            currentTaskid: res.data
          });
        }
      }
    })
  },
  //停止监控任务
  stopTask: function() {
    var that = this;
    var openid = that.data.currentTaskid;
    if (openid != '' && openid != null && openid != '0') {
      wx.request({
        url: app.globalData.url + '/check-tasks/stop',
        method: 'PUT',
        header: {
          'Authorization': 'Bearer ' + wx.getStorageSync('id_token'),
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          task_id: openid
        },
        success: res => {
          console.log("停止任务");
          console.log(res)
          that.setData({
            flagButton: '开始监控',
            backgroundColor: '#4D8AD7',
            currentTaskid: ''
          });

        }
      })
    } else {
      console.log('停止任务监控出现错误')
    }

  },
  watchBack: function(position) {
    let that = this;
    that.getRelationList();
    console.log('获得的位置：' + position)
    let latitude = position.split(",")[0];
    let longitude = position.split(",")[1];
    that.setData({
      catchIcon: that.data.temporaryhead,
      selectedUsername: that.data.temporaryusername
    })
    //发出获取当前位置的请求
    that.getMap(latitude, longitude);
    that.setPositionName(latitude, longitude);
  },
  //设置位置的名称描述
  setPositionName: function(latitude, longitude) {
    let that = this;
    wx.request({
      url: 'https://restapi.amap.com/v3/geocode/regeo',
      data: {
        key: '55e2591136e5d5aec54c9b1de500014e',
        location: longitude + "," + latitude,
        extensions: "all",
        s: "rsx",
        sdkversion: "sdkversion",
        logversion: "logversion"

      },
      success: function(res) {
        console.log(res)
        that.setData({
          textData: {
            name: res.data.regeocode.pois[0].name,
            desc: res.data.regeocode.formatted_address
          }
        })
        // console.log(JSON.stringify(res.data.regeocode.formatted_address));
      },
      fail: function(res) {

      }
    })

  },
  //创建关系
  createRelation: function(mainopenid, secondopenid) {

    let that = this;
    wx.request({
      url: app.globalData.url + '/relationships',
      method: 'POST',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('id_token'),
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        main_open_id: mainopenid,
        second_open_id: secondopenid
      },
      success: res => {
        console.log("创建用户间关系");
        console.log(res)

      }
    });

  },
  updateAuthority: function(type) {
    let that = this;
    wx.request({
      url: app.globalData.url + '/users/authority',
      method: 'PUT',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('id_token'),
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        open_id: wx.getStorageSync('open_id'),
        flag: type
      },
      success: res => {
        console.log('修改用户角色成功');
        console.log(res)
        wx.setStorageSync('authorities', res.data.authorities);
        if (wx.getStorageSync('authorities').indexOf("ROLE_ADMIN") > -1) {
          that.setData({
            admin_flag: true
          })
        }
      }
    });
  }



})